//账单列表相关Store
import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";

const billSlice = createSlice({
    name: 'bill',
    //数据状态state
    initialState: {
        billList: []
    },
    reducers: {
        //同步修改方法
        setBillList(state, action) {
            state.billList = action.payload
        },
        //添加账单
        addBill(state, action) {
            state.billList.push(action.payload)
        }
    }
})

//解构actionCreator
//actions表示所有action组成的对象
//const setBillList = billSlice.action.setBillList
const {setBillList, addBill} = billSlice.actions


//异步操作
const fetchBillList = () => {
    return async (dispatch) => {
        //编写异步请求
        const res = await axios.get('http://localhost:8888/ka')
        //触发同步reducer
        dispatch(setBillList(res.data))
    }
}

const addBillList = (data) => {
    return async (dispatch) => {
        //编写异步请求
        const res = await axios.post('http://localhost:8888/ka', data)
        //触发同步reducer
        dispatch(addBill(res.data))
    }
}

//导出actionCreator
export {fetchBillList, addBillList}


//导出单个reducer，reducers表示所有同步修改方法
const reducer = billSlice.reducer
export default reducer